package com.tanhua.mangement.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.Manager;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.UserManageApi;
import com.tanhua.dubbo.server.pojo.Managelogs;
import com.tanhua.mangement.utils.ManagerThreadLocal;
import com.tanhua.mangement.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserManageService {

    @Reference(version = "1.0.0")
    private UserManageApi userManageApi;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GetUserCenterService getUserCenterService;

    /**
     * 冻结用户
     *
     * @param userManageFrozenVo
     * @return
     */
    public Boolean userFreeze(UserManageFrozenVo userManageFrozenVo) {
        //1.获取管理员的操作人的id
        //todo 在这里直接创建一个
        //Integer adminId = 1;
        Manager manager = ManagerThreadLocal.get();
        Integer adminId = Convert.toInt(manager.getUid());
        //2.取出数据
        //需要冻结的用户id
        Integer userId = userManageFrozenVo.getUserId();
        //冻结的时间--枚举
        Integer freezingTime = userManageFrozenVo.getFreezingTime();
        //冻结的范围--枚举
        Integer freezingRange = userManageFrozenVo.getFreezingRange();
        //冻结的原因
        String reasonsForFreezing = userManageFrozenVo.getReasonsForFreezing();
        //冻结备注
        String frozenRemarks = userManageFrozenVo.getFrozenRemarks();
        /**
         * 这里判断一下传入的参数全部不为null
         */
        if (adminId == null || userId == null || freezingTime == null || freezingRange == null || !StrUtil.isAllNotEmpty(reasonsForFreezing, frozenRemarks)) {
            //有一个为null就直接进来
            return false;
        }

        //3.将数据传入到api中进行实现
        Boolean result = userManageApi.userFreeze(adminId, userId, freezingTime, freezingRange, reasonsForFreezing, frozenRemarks);

        //4.因为这里直接返回结果就行不管冻结成不成功,直接返回结果
        return result;

    }

    /**
     * 解冻用户
     *
     * @param userManageUnfrozenVo
     * @return
     */
    public Boolean userUnfreeze(UserManageUnfrozenVo userManageUnfrozenVo) {
        //1.获取管理员的操作人的id
        //todo 在这里直接创建一个
        // Integer adminId = 1;
        Manager manager = ManagerThreadLocal.get();
        Integer adminId = Convert.toInt(manager.getUid());

        //2.取出数据
        //需要解冻的用户id
        Integer userId = userManageUnfrozenVo.getUserId();
        //解冻的理由
        String frozenRemarks = userManageUnfrozenVo.getFrozenRemarks();

        /**
         * 这里判断一下传入的参数全部不为null
         */
        if (adminId == null || userId == null || !StrUtil.isNotEmpty(frozenRemarks)) {
            //有一个为null就直接进来
            return false;
        }

        //3.将数据传入到api中进行实现
        Boolean result = userManageApi.userUnfreeze(adminId, userId, frozenRemarks);

        //4.因为这里直接返回结果就行不管冻结成不成功,直接返回结果
        return result;
    }

    /**
     * 用户数据分页
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult userManageDataPage(Integer page, Integer pageSize, Integer id, String nickname, String city) {
        //创建返回对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //用户的数据id,我们直接获取,分页数据才是关键
        //1.我们通过用户的id升序进行查询
        QueryWrapper queryWrapper = new QueryWrapper();
        if (ObjectUtil.isEmpty(id) && ObjectUtil.isEmpty(nickname) && ObjectUtil.isEmpty(city)) {
            queryWrapper.orderByAsc("user_id");
        }
        if (ObjectUtil.isNotEmpty(id)) {

            queryWrapper.like("user_id", id);
        }
        if (ObjectUtil.isNotEmpty(nickname)) {

            queryWrapper.like("nick_name", nickname);
        }
        if (ObjectUtil.isNotEmpty(city)) {
            queryWrapper.like("city", city);
        }
        IPage<UserInfo> userInfoIPage = this.userInfoMapper.selectPage(new Page<UserInfo>(page, pageSize), queryWrapper);
        //封装总条数
        pageResult.setCounts((int) userInfoIPage.getTotal());
        //2.获取用户的id
        List<UserInfo> userInfoList = userInfoIPage.getRecords();
        List<Object> userIdList = CollUtil.getFieldValues(userInfoList, "userid");
        //3.遍历集合先将用户的信息封装进去UserInfo
        List<UserManageDataVo> userManageDataVoList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UserManageDataVo userManageDataVo = new UserManageDataVo();
            this.fillUserInfoToUserManageDataVo(userInfo, userManageDataVo);
            //userStatus
            //这里我们就直接进行调用方法进行查询
            String status = this.userStatus(userInfo.getUserId());
            if (StrUtil.equals("1", status)) {
                userManageDataVo.setUserStatus("1");
            } else if (StrUtil.equals("2", status)) {
                userManageDataVo.setUserStatus("2");
            }
            //todo 异常没有处理
            userManageDataVoList.add(userManageDataVo);
        }

        pageResult.setItems(userManageDataVoList);
        return pageResult;
    }

    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param userManageDataVo
     */
    private void fillUserInfoToUserManageDataVo(UserInfo userInfo, UserManageDataVo userManageDataVo) {
        BeanUtil.copyProperties(userInfo, userManageDataVo, "id");
        //id	integer 必须 用户ID
        userManageDataVo.setId(Convert.toInt(userInfo.getUserId()));
        //sex
        userManageDataVo.setSex(userInfo.getSex().getValue() == 1 ? "男" : "女");
        //剩余没有封装的
        //mobile
        //通过id进行查询后进行封装
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", Convert.toInt(userInfo.getUserId()));
        User user = this.userMapper.selectOne(queryWrapper);
        userManageDataVo.setMobile(user.getMobile());

        //logoStatus,直接写死
        userManageDataVo.setLogoStatus("通过");
        //userStatus
        //lastActiveTime
        //todo
        Managelogs managelogs = this.userManageApi.getLogs(userInfo.getUserId() + "");
        Long lastActiveTime = managelogs.getLogTime();
        userManageDataVo.setLastActiveTime(System.currentTimeMillis());


    }

    /**
     * 查询用户的状态
     *
     * @param userId
     */
    private String userStatus(Long userId) {
        /**
         * 冻结的话返回:1为正常，2为冻结
         */
        String result = this.userManageApi.userStatus(userId);
        return result;
    }

    /**
     * 查询用户的基本资料
     *
     * @param userId
     * @return
     */
    public UserManageBasicVo userManageBasic(String userId) {
        //1.创建返回的对象
        UserManageBasicVo userManageBasicVo = new UserManageBasicVo();
        //3.获取UserInfo
        QueryWrapper<UserInfo> userInfoQuery = new QueryWrapper<>();
        userInfoQuery.eq("user_id", Convert.toInt(userId));
        UserInfo userInfo = this.userInfoMapper.selectOne(userInfoQuery);
        //4.将userInfo中的数据直接复制到userManageBasicVo
        BeanUtil.copyProperties(userInfo, userManageBasicVo, "id");
        //id	integer 必须 用户ID
        userManageBasicVo.setId(Convert.toInt(userInfo.getUserId()));
        //sex	string 必须 性别 枚举: 男,女,未知
        userManageBasicVo.setSex(userInfo.getSex().getValue() == 1 ? "男" : "女");
        //income	integer  必须  收入==>类型不同
        userManageBasicVo.setIncome(Convert.toInt(userInfo.getIncome()));
        //created	integer  必须  注册时间  枚举: 1598608534811==>ui中是date
        userManageBasicVo.setCreated(userInfo.getCreated().getTime());


        //5.将user中的数据进行封装
        QueryWrapper<User> userQuery = new QueryWrapper<>();
        userQuery.eq("id", Convert.toInt(userId));
        User user = this.userMapper.selectOne(userQuery);
        //mobile	string 必须 手机号，即用户账号 最大长度: 11
        userManageBasicVo.setMobile(user.getMobile());

        //userStatus	string  必须  用户状态，1为正常，2为冻结  枚举: 1,2
        String userStatus = this.userStatus(Convert.toLong(userId));
        if (StrUtil.equals("1", userStatus)) {
            //userManageBasicVo.setUserStatus("正常");
            userManageBasicVo.setUserStatus("1");
        } else if (StrUtil.equals("2", userStatus)) {
            //userManageBasicVo.setUserStatus("冻结");
            userManageBasicVo.setUserStatus("2");
        }

        //countBeLiked	integer  必须  被喜欢人数
        //由于我们是管理员需要传入用户的id进行查询,因此,这里只能进行重写方法
        Integer countBeLiked = getUserCenterService.userCountBeLiked(Convert.toLong(userId));
        userManageBasicVo.setCountBeLiked(countBeLiked);

        //countLiked	integer 必须 喜欢人数
        Integer countLiked = getUserCenterService.userCountLiked(Convert.toLong(userId));
        userManageBasicVo.setCountLiked(countLiked);


        //countMatching	integer  必须  配对人数
        Integer countMatching = getUserCenterService.userEachLoveCount(Convert.toLong(userId));
        userManageBasicVo.setCountMatching(countMatching);

        //todo personalSignature	string 必须 个性签名 未知
        userManageBasicVo.setPersonalSignature("聂刚的qq昵称叫:某月某日");

        //todo lastActiveTime	integer  必须  最近活跃时间  枚举: 1598608534811 日志
        //查询日志表
        Managelogs managelogs = this.userManageApi.getLogs(userId);
        Long lastActiveTime = managelogs.getLogTime();
        userManageBasicVo.setLastActiveTime(lastActiveTime);
        //todo lastLoginLocation	string  必须  最近登录地 日志
        String place = managelogs.getPlace();
        userManageBasicVo.setLastLoginLocation(place);

        //2.返回对象
        return userManageBasicVo;
    }
}
